<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="1200px"
    :close-on-click-modal="false"
    destroy-on-close
    class="image-editor-dialog"
    :modal-class="'image-editor-modal'"
    align-center
  >
    <div class="image-editor-container">
      <!-- 左侧工具栏 -->
      <div
        class="tools-sidebar w-[180px] p-4 border-r border-gray-200 dark:border-gray-700"
      >
        <div class="tool-group mb-6">
          <div class="tool-title mb-2">旋转</div>
          <el-button-group class="w-full">
            <el-button @click="rotate(-90)" class="flex-1">
              <el-icon><Refresh /></el-icon>
              向左
            </el-button>
            <el-button @click="rotate(90)" class="flex-1">
              <el-icon class="transform rotate-180"><Refresh /></el-icon>
              向右
            </el-button>
          </el-button-group>
        </div>

        <div class="tool-group mb-6">
          <div class="tool-title mb-2">缩放</div>
          <el-button-group class="w-full">
            <el-button @click="zoom(2)" class="flex-1">
              <el-icon><ZoomIn /></el-icon>
              放大
            </el-button>
            <el-button @click="zoom(-0.5)" class="flex-1">
              <el-icon><ZoomOut /></el-icon>
              缩小
            </el-button>
          </el-button-group>
        </div>

        <div class="tool-group">
          <el-button @click="reset" class="w-full">
            <el-icon><RefreshRight /></el-icon>
            重置
          </el-button>
        </div>

        <div class="upload-area mt-8">
          <el-upload
            class="image-uploader"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            :on-change="handleFileChange"
            drag
          >
            <div class="upload-content">
              <el-icon :size="32"><Upload /></el-icon>
              <div class="upload-text mt-2">拖拽图片到此处或点击上传</div>
              <div class="upload-hint mt-1">支持 jpg、png 格式，最大 2MB</div>
            </div>
          </el-upload>
          <div class="paste-hint mt-2 text-center text-gray-500 text-sm">
            您也可以直接粘贴图片 (Ctrl + V)
          </div>
        </div>
      </div>

      <!-- 中间编辑区域 -->
      <div class="edit-area flex-1 p-4">
        <VueCropper
          ref="cropperRef"
          :img="tempImage"
          :outputSize="1"
          :outputType="'jpeg'"
          :info="true"
          :full="true"
          :canMove="true"
          :canMoveBox="true"
          :original="false"
          :autoCrop="true"
          :fixed="true"
          :fixedNumber="[aspectRatio, 1]"
          :centerBox="true"
          :high="true"
          :infoTrue="true"
          @realTime="realTime"
        />
      </div>

      <!-- 右侧历史图片 -->
      <div
        class="history-sidebar w-[200px] p-4 border-l border-gray-200 dark:border-gray-700"
      >
        <div class="sidebar-title mb-4">历史图片</div>
        <el-scrollbar height="500px">
          <div class="history-list">
            <div
              v-for="(image, index) in historyImages"
              :key="index"
              class="history-item mb-4"
              :class="{ selected: selectedHistoryImage?.url === image.url }"
              @click="selectHistoryImage(image)"
            >
              <el-image
                :src="image.url"
                fit="cover"
                :preview-src-list="[image.url]"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="image-info">
                <span class="image-time">{{
                  formatDate(image.createTime)
                }}</span>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="info" @click="saveDraft" :loading="savingDraft">
          保存草稿
        </el-button>
        <el-button type="primary" @click="handleUpload" :loading="uploading">
          确认上传
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import {
  Plus,
  Picture,
  Refresh,
  ZoomIn,
  ZoomOut,
  RefreshRight,
  Upload,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { VueCropper } from "vue-cropper";
import "vue-cropper/dist/index.css";
import { useDark } from "@vueuse/core";
import axios from "axios";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: "图片编辑",
  },
  uploadAction: {
    type: String,
    required: true,
  },
  headers: {
    type: Object,
    default: () => ({}),
  },
  aspectRatio: {
    type: Number,
    default: 1,
  },
  historyImages: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:modelValue", "success", "select"]);

// 暗黑模式
const isDark = useDark();

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

// 裁剪相关
const cropperRef = ref(null);
const tempImage = ref("");
const uploading = ref(false);

// 历史图片选择
const selectedHistoryImage = ref(null);

// 草稿相关
const savingDraft = ref(false);
const draftKey = computed(() => `image-editor-draft-${props.uploadAction}`);

// 处理文件选择
const handleFileChange = (file) => {
  const isImage = file.raw.type.startsWith("image/");
  const isLt2M = file.raw.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return;
  }

  // 创建本地预览URL
  const reader = new FileReader();
  reader.onload = (e) => {
    tempImage.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);
};

// 图片编辑功能
const rotate = (deg) => {
  if (cropperRef.value) {
    if (deg > 0) {
      cropperRef.value.rotateRight();
    } else {
      cropperRef.value.rotateLeft();
    }
  }
};

const zoom = (scale) => {
  if (cropperRef.value) {
    cropperRef.value.changeScale(scale);
  }
};

const reset = () => {
  if (cropperRef.value) {
    cropperRef.value.refresh();
    // 重置后恢复默认缩放
    cropperRef.value.changeScale(1);
  }
};

// 添加实时预览回调
const realTime = (data) => {
  // 可以在这里处理实时预览数据
  console.log("实时预览数据:", data);
};

// 选择历史图片
const selectHistoryImage = (image) => {
  selectedHistoryImage.value = image;
};

// 处理上传
const handleUpload = async () => {
  if (!cropperRef.value || !tempImage.value) {
    ElMessage.warning("请先选择或上传图片");
    return;
  }

  try {
    uploading.value = true;

    // 获取裁剪后的图片数据
    const cropData = await new Promise((resolve) => {
      cropperRef.value.getCropData((data) => {
        resolve(data);
      });
    });

    // 模拟上传成功
    emit("success", {
      url: cropData, // 直接使用裁剪后的base64数据作为url
      file: new File([cropData], "cropped-image.jpg", { type: "image/jpeg" }),
    });

    // 清除草稿
    localStorage.removeItem(draftKey.value);

    handleCancel();
    ElMessage.success("处理成功");
  } catch (error) {
    console.error("处理失败:", error);
    ElMessage.error("处理失败，请重试");
  } finally {
    uploading.value = false;
  }
};

// 保存草稿
const saveDraft = async () => {
  if (!cropperRef.value || !tempImage.value) {
    ElMessage.warning("请先选择或上传图片");
    return;
  }

  try {
    savingDraft.value = true;

    // 获取裁剪后的图片数据
    const cropData = await new Promise((resolve) => {
      cropperRef.value.getCropData((data) => {
        resolve(data);
      });
    });

    // 保存草稿数据
    const draftData = {
      image: tempImage.value,
      cropData,
      timestamp: Date.now(),
    };

    // 保存到 localStorage
    localStorage.setItem(draftKey.value, JSON.stringify(draftData));

    ElMessage.success("草稿保存成功");
  } catch (error) {
    console.error("保存草稿失败:", error);
    ElMessage.error("保存草稿失败，请重试");
  } finally {
    savingDraft.value = false;
  }
};

// 加载草稿
const loadDraft = () => {
  try {
    const draftStr = localStorage.getItem(draftKey.value);
    if (!draftStr) return;

    const draft = JSON.parse(draftStr);

    // 检查草稿是否过期（24小时）
    if (Date.now() - draft.timestamp > 24 * 60 * 60 * 1000) {
      localStorage.removeItem(draftKey.value);
      return;
    }

    // 加载图片
    tempImage.value = draft.image;

    // 等待图片加载完成后设置裁剪数据
    setTimeout(() => {
      if (cropperRef.value && draft.cropData) {
        tempImage.value = draft.cropData;
      }
    }, 300);

    ElMessage.info("已加载上次保存的草稿");
  } catch (error) {
    console.error("加载草稿失败:", error);
  }
};

// 监听对话框打开
watch(
  () => dialogVisible.value,
  (newVal) => {
    if (newVal) {
      // 对话框打开时加载草稿
      loadDraft();
    }
  },
);

// 取消操作时重置步骤
const handleCancel = () => {
  tempImage.value = "";
  selectedHistoryImage.value = null;
  dialogVisible.value = false;
  // 可以选择是否在取消时保留草稿
  // localStorage.removeItem(draftKey.value);
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "";
  return new Date(date).toLocaleString();
};
</script>

<style lang="scss" scoped>
.image-editor-dialog {
  :deep(.el-dialog__body) {
    @apply p-0;
  }

  :deep(.el-dialog) {
    @apply my-0;
    margin-top: 5vh !important;
  }
}

.image-editor-container {
  @apply flex h-[600px];
}

:deep(.image-editor-modal) {
  @apply bg-black/60 backdrop-blur-sm;
}

.tools-sidebar {
  .tool-group {
    .tool-title {
      @apply text-sm font-medium text-gray-700 dark:text-gray-300;
    }
  }

  .upload-area {
    @apply border-t border-gray-200 dark:border-gray-700 pt-6;

    .upload-content {
      @apply flex flex-col items-center justify-center p-6 
             border-2 border-dashed border-gray-200 dark:border-gray-700
             rounded-lg cursor-pointer transition-colors duration-300;

      &:hover {
        @apply border-primary-500 dark:border-primary-500;
      }

      .el-icon {
        @apply text-gray-400 dark:text-gray-500;
      }

      .upload-text {
        @apply text-gray-600 dark:text-gray-300 text-sm;
      }

      .upload-hint {
        @apply text-gray-400 dark:text-gray-500 text-xs;
      }
    }
  }
}

.edit-area {
  @apply bg-gray-50 dark:bg-gray-900;

  :deep(.vue-cropper) {
    @apply h-full max-w-[700px] mx-auto;
  }
}

.history-sidebar {
  .sidebar-title {
    @apply text-sm font-medium text-gray-700 dark:text-gray-300;
  }

  .history-list {
    .history-item {
      @apply relative rounded-lg overflow-hidden cursor-pointer
             ring-2 ring-transparent hover:ring-primary-500
             transition-all duration-300;

      &.selected {
        @apply ring-2 ring-primary-500;
      }

      .el-image {
        @apply aspect-square w-full;
      }

      .image-info {
        @apply absolute bottom-0 left-0 right-0
               bg-black/50 backdrop-blur-sm
               p-2 text-white text-xs;
      }

      .image-error {
        @apply flex items-center justify-center h-full bg-gray-100 dark:bg-gray-800;

        .el-icon {
          @apply text-gray-400 dark:text-gray-600 text-xl;
        }
      }
    }
  }
}

.dialog-footer {
  @apply flex justify-end gap-2 p-4 bg-gray-50 dark:bg-gray-800
         border-t border-gray-200 dark:border-gray-700;

  :deep(.el-button--info) {
    @apply bg-gray-500 border-gray-500 hover:bg-gray-600 hover:border-gray-600;
  }
}
</style>
